#!/usr/bin/env python
# coding=utf-8

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

import logging,logging.config
from vavava import util
from vavava.dispatcher import Dispatcher
from vavava.workshop import WorkShop

__author__ = 'vavava'

def usage():
    print ( """tracker [-d debug_level][-t timeout][-ids id[|id]]""")

def main():
    import time
    from sys import argv
    from config_file import GripperConfig
    config=GripperConfig()

    argv_dic=util.parse_argvs(argv)
    if argv_dic and argv_dic.get('-config'):
        config.load(argv_dic.get('-config'))
    else:
        config.load('tracker.conf')

    logging.config.fileConfig(config.log_config_file)
    log=logging.getLogger(config.logger)

    if argv_dic:
        if argv_dic.get('-d'):    config.debug_level=int(argv_dic.get('-d'))
        if argv_dic.get('-t'):    config.sock_timeout=float(argv_dic.get('-t'))
        #if argv_dic.get('-ids'):  config.userTokens=argv_dic.get('-ids').split('|')

    display_str="""Tracking Begin[%s]: Debug level=%d Socket timeout=%f """
    log.info(display_str%(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())),
                          config.debug_level,config.sock_timeout))

    # 开始工作 ===============================================================
    ws = WorkShop( minsize=config.work_queue_size, log=log )
    dsp = Dispatcher( ws, log )

    from spiders.track_gripper import TrackGripperWork,\
        DefaultExceptionProcessor,DefaultResultProcessor
    from ltypes.track_item import TraceItemList

    itemlist = TraceItemList.getItemList()

    log.info("获取货物列表(%d)"%len(itemlist.items_all))
    log.info("启动车间")
    ws.StartWork()
    log.info("启动分配器")
    dsp.running_start()

    index = 0
    for item in itemlist.items_all:
        log.info("添加一个工作项：%s, 执行间隔 %f"%(item,config.chk_period))
        work = TrackGripperWork(dbObj=None,itemID=item,log=log)
        dsp.AddPackage(work=work,period=config.chk_period)
        index += 1


    # 工作完成 ===============================================================
    try:
        while True:
            #print('running')
            time.sleep(1)
    except(KeyboardInterrupt):
        log.info('hello DB  user canceled!!')

    log.info('gripper:stopped')

    log.info("""Tracking ended at %s"""%
             time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))

if __name__ == '__main__':
    main()
